package com.wf.service.impl;


import cn.hutool.core.util.StrUtil;
import com.wf.domain.SysPermission;
import com.wf.domain.SysRole;
import com.wf.domain.SysUser;
import com.wf.mapper.SysUserMapper;
import com.wf.secure.services.SecureUser;
import com.wf.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Security 用户服务实现
 *
 * author: mpk
 * CreateTime: 2021/04/23
 * */
@Component
@Slf4j
public class SecureUserService implements UserDetailsService {


    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysUserService sysUserService;

    /**
     * 加载用户信息
     *
     * */
    @Override
    public SecureUser loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("loadUserByUsername:{}",username);

        SysUser sysUser = sysUserMapper.selectByUsername(username);

        if(sysUser==null) {
            throw new UsernameNotFoundException("USERNAME NOT SUPPORT");
        }
        if(sysUser.getStatus()==1)
        {
            throw new UsernameNotFoundException("USERNAME IS LOCKED");
        }

        List<SysRole> roles = loadRoles(sysUser.getUserId());
        sysUser.setRoles(roles);
        List<String> roleIds = roles.stream().map(SysRole::getRoleId).collect(Collectors.toList());
        sysUser.setAuthorities(loadAuthorities(roleIds));

        return sysUser;

    }
        public Collection<? extends GrantedAuthority> loadAuthorities(List<String> roleIds){
            List<SimpleGrantedAuthority> authoritySet = new ArrayList<>();
            List<SysPermission> permissions ;
            for (String roleId : roleIds) {
                 permissions = sysUserService.permission(roleId);
                for (SysPermission permission : permissions) {
                    if(permission.getIsMenu()==0&& StrUtil.isNotEmpty(permission.getPerm()))
                    {
                        SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getPerm());
                        authoritySet.add(authority);
                    }
                }
                permissions.clear();
            }

            return authoritySet;
        }

        public List<SysRole> loadRoles(String userId) {
            return sysUserService.role(userId);
        }
    }


